package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import com.project.util.ValidateAdd;
import com.project.util.ValidateUpdate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("add")
    public String add(@Validated(ValidateAdd.class) UserBean user,//@Valid 表示该对象的属性需要进行验证
                      BindingResult result) throws Exception {//BindingResult用于判断验证是否通过，以绑定出错信息
        if(result.hasErrors()){//判断是否有错误消息
            //得到错误集合
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            //将错误信息转化为json字符串，发送给客户端
            String errorStr = om.writeValueAsString(errorList);
            return errorStr;
        }

        System.out.println("执行添加业务");
        return "ok";
    }

    @RequestMapping("update")
    public String update(@Validated(ValidateUpdate.class) UserBean user,//@Valid 表示该对象的属性需要进行验证
                         BindingResult result) throws Exception {//BindingResult用于判断验证是否通过，以绑定出错信息
        if(result.hasErrors()){//判断是否有错误消息
            //得到错误集合
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            //将错误信息转化为json字符串，发送给客户端
            String errorStr = om.writeValueAsString(errorList);
            return errorStr;
        }

        System.out.println("执行修改业务");
        return "ok";
    }
}
